const { NAME_OR_PASSWORD_IS_REQUIRED, NAME_IS_EXISTS } = require("../constant");
const userService = require("../service/user.server");
const md5password = require("../utils/md5password");

const verifyUser = async (ctx, next) => {
  //用户验证逻辑校验
  const user = ctx.request.body;
  //1用户名和密码不能为空
  const { name, password } = user;
  if (!name || !password) {
    return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
  }
  //2写入数据库之前判断是否重复
  const value = await userService.findUserByName(name);
  if (value.length) {
    return ctx.app.emit("error", NAME_IS_EXISTS, ctx);
  }
  //3执行下一个中间件
  await next();
};

const handlePassWord = async (ctx, next) => {
  //取出密码
  const { password } = ctx.request.body;

  //对密码进行加密
  ctx.request.body.password = md5password(password);

  //3执行下一个中间件
  await next();
};




module.exports = { verifyUser, handlePassWord };
